//
//  ExternalMembersViewController.swift
//  willdo
//
//  Created by zz on 3/31/18.
//  Copyright © 2018 will do. All rights reserved.
//

import UIKit

class ExternalMembersViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//     [(key: String, value: [ContactInfo])]
    
    let tableView = UITableView(frame: CGRect.zero, style: .plain)
    let noContact = UILabel()
    
    var sorted = getSortedName(info: [])
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        view.addSubview(noContact)
        tableView.backgroundColor = UIColor(hexString:"#f1f2f6")
        self.automaticallyAdjustsScrollViewInsets = false
        self.edgesForExtendedLayout = .init(rawValue: 0)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        let ui = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 10))
        ui.backgroundColor = UIColor.clear
        tableView.tableHeaderView = ui
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        tableView.delegate = self
        tableView.dataSource = self
        
        noContact.isHidden = true
        noContact.text = "暂无联系人"
        noContact.font = UIFont(name: "PingFang SC", size: 32)
        noContact.textColor = UIColor(hexString:"#9d9fa8")
        noContact.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let modle = DBTool.shareDBTool().loadData() else {
            tableView.isHidden = true
            noContact.isHidden = false
            return
        }
        if modle.count == 0{
            tableView.isHidden = true
            noContact.isHidden = false
            return
        }
        sorted = getSortedName(info: modle)
        tableView.isHidden = false
        noContact.isHidden = true
        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "extern")
        if cell == nil{
            cell = UITableViewCell(style: .value1, reuseIdentifier: "extern")
        }
        let info = sorted[indexPath.section].value[indexPath.row]
        cell?.textLabel?.text = info.name
        cell?.textLabel?.textColor = UIColor(hexString: "2f3f59")
        cell?.textLabel?.font = UIFont(name: "PingFang SC", size: 17)
        cell?.detailTextLabel?.text = info.position
        cell?.detailTextLabel?.textColor = UIColor(hexString:"#9d9fa8")
        cell?.detailTextLabel?.font = UIFont(name: "PingFang SC", size: 14)
        return cell!
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sorted[section].value.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sorted.count
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView = UIView()
        headView.backgroundColor = UIColor(hexString: "#f1f2f6")
        let titleLable = UILabel()
        titleLable.text = sorted[section].key
        titleLable.textColor = UIColor(hexString: "#cecfd3")
        headView.addSubview(titleLable)
        titleLable.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
        }
        return headView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {        
        let infoVC = UIViewController()
        infoVC.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
        infoVC.view = ExternalMemberView(frame: view.frame, model: sorted[indexPath.section].value[indexPath.row])
        infoVC.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(infoVC, animated: true)
        tableView.cellForRow(at: indexPath)?.isSelected = false
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    // Override to support editing the table view.
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete){
            // Delete the row from the data source
            DBTool.shareDBTool().removeDataById(id: sorted[indexPath.section].value[indexPath.row].id)
            //            result![indexPath.row].removeCode()
            sorted[indexPath.section].value.remove(at: indexPath.row)
            if sorted[indexPath.section].value.count == 0 {
                sorted.remove(at: indexPath.section)
                tableView.reloadData()
            }else{
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            print(sorted)
            if sorted.count == 0{
                tableView.isHidden = true
                noContact.isHidden = false
            }
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }

    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 24
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView(frame: CGRect.zero)
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.00001
    }
    
}
